package com.acheli.rideable.functionLathes;

import com.acheli.ACHeli;
import com.acheli.registry.network.ACHMessages;
import com.acheli.registry.network.packet.ComponentSetupC2SPacket;
import com.acheli.registry.network.packet.ComponentSpawnC2SPacket;
import com.acheli.rideable.entites.ComponentEntity;
import com.acheli.rideable.entites.RideableEntity;
import com.acheli.utils.physics.PhysicsObject;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;

import java.util.*;

public class RideableFL extends RotateAbleEntityFL {
    public PhysicsObject rideablePhysicsObject = new PhysicsObject();
    private double mass = 0.0; // 质量，单位可以是kg
    private Vec3 force = Vec3.ZERO;
    protected final HashMap<Integer, ComponentFL> componentGroup = new HashMap<>();

    public HashMap<Integer, ComponentFL> getComponentGroup () {
        return componentGroup;
    }

    public void setMass(double mass) {
        this.mass = mass;
    }

    public double getMass() {
        double massInAll = this.mass;
        for (ComponentFL componentFL : componentGroup.values().stream().toList()) {
            massInAll += componentFL.getMass();
        }
        return massInAll;
    }

    public void addForce(Vec3 ad) {
        force = force.add(ad);
    }
    public void addForce(Double x, Double y, Double z) {
        force = force.add(x, y, z);
    }

    public Vec3 getForce() {
        return force;
    }

    public void addComponent(ComponentFL componentFL) {
        if (getComponentFLByID(componentFL.ID) == null) {
            componentGroup.put(componentFL.hashCode(), componentFL);
        } else {
            ACHeli.LOGGER.warn("Attempt to add componentFL. The component ID \"%s\" is already occupied".formatted(componentFL.ID));
        }

    }

    public void requestMountComponents(RideableEntity rideable) {

            // 用于收集需要处理的ID
            Set<String> missingIDs = new HashSet<>();
            // 第一次遍历：同时处理乘客和组件组ID，减少循环次数
            Map<String, ComponentEntity> passengers = new HashMap<>();
            for (Entity entity : rideable.getPassengers()) { // 直接遍历集合，避免创建中间List
                if (entity instanceof ComponentEntity componentEntity) {
                    String id = componentEntity.getID();
                    passengers.put(id, componentEntity);
                }
            }
            // 第二次遍历：直接检查组件组ID是否在乘客集合中
            for (ComponentFL functionLathe : componentGroup.values()) {
                String ID = functionLathe.ID;
                if (passengers.containsKey(ID)) { // HashSet的contains是O(1)操作
                    if (rideable.level().isClientSide) {
                        ComponentEntity component = passengers.get(ID);
                        component.setUp(rideable, functionLathe);
                        ACHMessages.sendToServer(new ComponentSetupC2SPacket(rideable.getUUID(), component.getUUID(), ID));
                    }
                } else {
                    missingIDs.add(ID);
                }
            }
            if (rideable.level().isClientSide) {
                for (String missingID : missingIDs.stream().toList()) {
                    ACHMessages.sendToServer(new ComponentSpawnC2SPacket(rideable.getUUID(), missingID)); //需要发送所有不存在的ID
                }
            }

            for (String ID : passengers.keySet().stream().toList()) { //清理缓存
                ComponentEntity component = passengers.get(ID);
                if (getComponentFLByID(ID) == null) {
                    component.kill();
                }
            }



    }

    public List<ComponentFL> getComponentFLList() {
        return componentGroup.values().stream().toList();
    }

    public ComponentFL getComponentFLByID(String ID) {
        ComponentFL target = null;
        for (ComponentFL componentBase : componentGroup.values()) {
            if (Objects.equals(componentBase.ID, ID)) {
                target = componentBase;
                break;
            }
        }
        return target;
    }


}
